package com.david.videoapp.adapter

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.david.videoapp.ChannelBean
import com.david.videoapp.R
import com.david.videoapp.VideoApplication

class ChannelAdapter : RecyclerView.Adapter<ChannelAdapter.ChannelHolder>(), View.OnClickListener {
    private var channels = ArrayList<ChannelBean>()
    private var lastSelectView:TextView? = null
    var onChannelSelectListener: OnChannelSelectListener? = null

    var currentPosition = 0

    private val selectTextColor = Color.GRAY
    private val normalTextColor = Color.WHITE

    private val selectBgColor = VideoApplication.instance.getColor(R.color.color_channel_select)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChannelHolder {
        return ChannelHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_channel, parent, false))
    }

    override fun getItemCount(): Int {
        return channels.size
    }

    override fun onBindViewHolder(holder: ChannelHolder, position: Int) {
        holder.title.text = channels[position].title
        holder.title.tag = position

        if (position == currentPosition) {
            holder.title.setBackgroundResource(R.color.color_channel_select)
            holder.title.setTextColor(selectTextColor)

            if (lastSelectView == null) {
                lastSelectView = holder.title
            }
        } else {
            holder.title.setBackgroundResource(R.color.color_channel)
            holder.title.setTextColor(normalTextColor)
        }
    }

    fun setChannels(channels:ArrayList<ChannelBean>){
        this.channels = channels
        notifyDataSetChanged()
    }

    fun getCurrentChannel(): ChannelBean {
        return channels[currentPosition]
    }

    override fun onClick(v: View?) {
        if (v == null) {
            return
        }

        lastSelectView?.setBackgroundColor(Color.TRANSPARENT)
        lastSelectView?.setTextColor(normalTextColor)
        v.setBackgroundColor(selectBgColor)
        v as TextView
        v.setTextColor(selectTextColor)
        lastSelectView = v


        currentPosition = v.tag as Int
        onChannelSelectListener?.onChannelSelect(currentPosition, channels[currentPosition])
    }

    inner class ChannelHolder(itemView: View):RecyclerView.ViewHolder(itemView){
        var title:TextView = itemView as TextView
        init {
            title.setOnClickListener(this@ChannelAdapter)
        }
    }

    interface OnChannelSelectListener{
        fun onChannelSelect(position: Int, channelBean: ChannelBean)
    }
}